<?php
namespace User\Controller;

use Common\Controller\HomebaseController;

class AddressController extends HomebaseController {
	
	public $user_id = 0;
	public $address_id;
	
	public function _initialize() {       
        parent::_initialize();		
		$this->user_id=sp_get_current_userid();	
	}
    // 收货地址
	public function index(){
		$addressType = I('get.type');
		$this->address_id = $addressType;
		if($addressType == 'add'){
			$this->addAddress();
		}else{
			$this->editAddress();
		}
		
		$this->display(":address");
	}
	
	//获取默认地址
	public function getAddress(){
		$def_address = M('UserAddress')->where(array('user_id' => $this->user_id,'is_default'=>1))->find();
		if($def_address){
        	$area_id = array();        	
        	$area_id[] = $def_address['province'];
            $area_id[] = $def_address['city'];
            $area_id[] = $def_address['district'];
            $area_id[] = $def_address['twon'];                          
            $area_id = array_filter($area_id);
        	$area_id = implode(',', $area_id);
        	$regionList = M('address')->where("id in ($area_id)")->getField('id,name');
        	$this->assign('regionList', $regionList);
        }
		$this->assign('def_address', $def_address);
		$this->display(":default_address");
	}
	
	
	public function ajax_address(){
		$this->display(":ajax_address");
	}
	//ajax获取地址列表
	public function ajaxAddress(){
		$model = M('UserAddress');
        $address_list = $model->where('user_id = '.$this->user_id)->order("is_default desc")->select();
        if($address_list){
        	$area_id = array();
        	foreach ($address_list as $val){
        		$area_id[] = $val['province'];
                        $area_id[] = $val['city'];
                        $area_id[] = $val['district'];
                        $area_id[] = $val['twon'];                        
        	}    
            $area_id = array_filter($area_id);
        	$area_id = implode(',', $area_id);
        	$regionList = M('address')->where("id in ($area_id)")->getField('id,name');
        	$this->assign('regionList', $regionList);
        }
        
                     
        $this->assign('address_list', $address_list);
        $this->display(":ajax_address");
	}
	
	
	//添加地址
	public function addAddress(){
		if(IS_POST){
			$data = I('post.');
			$data['user_id'] = $this->user_id;
			$model = D('UserAddress');
			$count = $model->where(array('user_id'=>$this->user_id))->count();
			$data['is_default'] = empty($count) ? 1 : 0; //没有地址就设为默认
			if($model->create() !== false){
				$address = $model->add($data);
				if($address){
					$result = array('status'=>1,'msg'=>'添加成功');
				}else{
					$result = array('status'=>-100,'msg'=>'添加失败');
				}
			}else{
				$this->error($model->getError());
			}
			exit(json_encode($result));
		}
		
		$province = M('address')->where(array('parent_id'=>0,'level'=> 1))->select();
        $this->assign('province',$province);
	}
	
	//编辑地址
	public function editAddress(){
		$address_mobel = M('address');
		$address = M('UserAddress')->where(array('address_id'=>$this->address_id,'user_id'=>$this->user_id))->find();
		
		if(IS_POST){
			$data = I('post.');
			$data['is_default'] = 1;
			
			$model = D('UserAddress');
			if($model->create() !== false){
				$address = $model->where(array('address_id'=>I('post.address_id'),'user_id'=>$this->user_id))->save($data);
				if($address !== false){
					$result = array('status'=>1,'msg'=>'保存成功');
				}else{
					$result = array('status'=>-100,'msg'=>'保存失败');
				}
			}else{
				$this->error($model->getError());
			}
			exit(json_encode($result));
		}
		$province = $address_mobel->where(array('level'=> 1))->select();
		$city = $address_mobel->where(array('parent_id'=>$address['province'],'level'=> 2))->select();
		$district = $address_mobel->where(array('parent_id'=>$address['city']))->select();
		//print_r($district);
		if($address['twon']){
        	$twon = M('address')->where(array('parent_id'=>$address['district'],'level'=>4))->select();
        	$this->assign('twon',$twon);
        }
		$this->assign('province',$province);
		$this->assign('city',$city);
		$this->assign('district',$district);
		$this->assign('address',$address);
	}
	
	//获取地区地址
	public function getRegion(){
        $parent_id = I('get.parent_id');
        $selected = I('get.selected',0);  
		
        $data = M('address')->where("parent_id=$parent_id")->select();
        $html = '';
        if($data){
            foreach($data as $h){
            	if($h['id'] == $selected){
            		$html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
            	}
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        echo $html;
    }
	
	//获取乡镇地址
	public function getTwon(){
    	$parent_id = I('get.parent_id');
    	$data = M('address')->where("parent_id=$parent_id")->select();
    	$html = '';
    	if($data){
    		foreach($data as $h){
    			$html .= "<option value='{$h['id']}'>{$h['name']}</option>";
    		}
    	}
    	if(empty($html)){
    		echo '0';
    	}else{
    		echo $html;
    	}
    }
	
	//设为默认地址
	public function ajaxDefaultAddress(){
		$id = I('get.id');
		if(isset($id)){
			M('UserAddress')->where(array('user_id'=>$this->user_id))->save(array('is_default'=>0)); 
			M('UserAddress')->where(array('user_id'=>$this->user_id,'address_id'=>$id))->save(array('is_default'=>1));
		}		 
	}
	
	/*
     * 删除收货地址
     */
    public function del_address(){
        $id = I('get.id');
        
        $address = M('user_address')->where("address_id = $id")->find();
        $row = M('user_address')->where(array('user_id'=>$this->user_id,'address_id'=>$id))->delete();                
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if($address['is_default'] == 1)
        {
            $address2 = M('user_address')->where("user_id = {$this->user_id}")->find();            
            $address2 && M('user_address')->where("address_id = {$address2['address_id']}")->save(array('is_default'=>1));
        }        
        if($row){
            $result = array('status'=>1,'msg'=>'删除成功');
        }else{
            $result = array('status'=>-9,'msg'=>'删除失败');
		}
		exit(json_encode($result));
    }
	
}